package com.example.service;

import com.example.dto.OrderCreateDTO;
import com.example.entity.Order;
import com.example.repository.OrderRepository;
import io.camunda.zeebe.client.ZeebeClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OrderService {

    private final OrderRepository orderRepository;
    private final ZeebeClient zeebeClient;

    /**
     * 创建订单并启动 Camunda 流程
     */
    @Transactional
    public Order createOrder(OrderCreateDTO createDTO) {
        // 1. 生成订单编号（UUID 简化）
        String orderNo = "ORDER_" + UUID.randomUUID().toString().replace("-", "").substring(0, 10);

        // 2. 保存订单（初始状态：CREATED）
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setProductName(createDTO.getProductName());
        order.setProductCount(createDTO.getProductCount());
        order.setTotalAmount(createDTO.getTotalAmount());
        order.setStatus(Order.OrderStatus.CREATED);
        Order savedOrder = orderRepository.save(order);
        BigDecimal totalAmount = createDTO.getTotalAmount();
        // 3. 启动 Camunda 订单流程
        zeebeClient.newCreateInstanceCommand()

                .bpmnProcessId("order-flow2")  // 流程定义 ID（与 BPMN 文件一致）
                .latestVersion()  // 使用最新版本流程
                .variables("{\"orderNo\":\"" + orderNo + "\",\"totalAmount\":" + totalAmount + "}")  // 传递订单编号作为流程变量
                .send()
                .join();

        return savedOrder;
    }

    /**
     * 根据订单编号查询订单
     */
    public Order getOrderByNo(String orderNo) {
        return orderRepository.findByOrderNo(orderNo)
                .orElseThrow(() -> new RuntimeException("订单不存在：" + orderNo));
    }

    /**
     * 更新订单状态
     */
    @Transactional
    public void updateOrderStatus(String orderNo, Order.OrderStatus status) {
        Order order = getOrderByNo(orderNo);
        order.setStatus(status);
        orderRepository.save(order);
    }
}